<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="所属产品" prop="productId">
                <el-select @change="handleQuery" filterable v-model="queryParams.productId" placeholder="请选择产品"
                           clearable>
                    <el-option v-for="dict in productList" :key="dict.productId" :label="dict.productName"
                               :value="dict.productId"/>
                </el-select>
            </el-form-item>
            <el-form-item label="展示语言" prop="languageCode">
                <el-select @change="handleQuery" filterable v-model="queryParams.languageCode"
                           placeholder="请选择展示语言"
                           clearable>
                    <el-option v-for="dict in languageList" :key="dict.languageId"
                               :label="`${dict.languageCode}-${dict.zhName}`"
                               :value="dict.languageCode"/>
                </el-select>
            </el-form-item>
            <el-form-item label="值" prop="translateVal">
                <el-input
                        v-model="queryParams.translateVal"
                        placeholder="请输入值"
                        clearable
                        @keyup.enter="handleQuery"
                        @change="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['business:Translate:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['business:Translate:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col v-if="queryParams.productId" :span="1.5">
                <el-button type="info" plain icon="Upload" @click="handleImport"
                           v-hasPermi="['business:Translate:import']">导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['business:Translate:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table row-key="translateId" border v-loading="loading" :data="TranslateList"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="版本编号" align="center" prop="translateId"/>
            <el-table-column label="所属产品" align="center" prop="product.productName"/>
            <el-table-column label="语言" align="center" prop="language.zhName"/>
            <el-table-column label="翻译值" align="center" prop="translateVal"/>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button v-if="!scope.row.parentId" link type="warning" icon="Download" @click="handleExportSimple(scope.row)"
                               v-hasPermi="['business:Translate:export']">导出
                    </el-button>
                    <el-button v-if="!scope.row.parentId" link type="primary" icon="Edit"
                               @click="handleUpdate(scope.row)"
                               v-hasPermi="['business:Translate:edit']">修改
                    </el-button>
                    <el-button v-if="!scope.row.parentId" link type="danger" icon="Delete"
                               @click="handleDelete(scope.row)"
                               v-hasPermi="['business:Translate:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改翻译版本对话框 -->
        <el-dialog :title="title" v-model="open" width="60%" append-to-body>
            <el-form ref="TranslateRef" :model="form" :rules="rules" label-width="100">
                <el-form-item label="所属产品" prop="productId">
                    <el-select :disabled="hasChild" class="f-full" v-model="form.productId" placeholder="请选择产品">
                        <el-option v-for="dict in productList" :key="dict.productId" :label="dict.productName"
                                   :value="dict.productId"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="源语言" prop="languageCode">
                    <el-select :disabled="hasChild" filterable class="f-full" v-model="form.languageCode"
                               placeholder="请选择源语言">
                        <el-option v-for="dict in languageList" :key="dict.languageId"
                                   :label="`${dict.languageCode}-${dict.zhName}`"
                                   :value="dict.languageCode"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="待翻译文本" prop="translateVal">
                    <el-input :disabled="hasChild" type="textarea" show-word-limit :maxlength="maxlength"
                              v-model="form.translateVal"
                              placeholder="请输入值"/>
                </el-form-item>
                <el-divider>
                    <div>目标语言</div>
                </el-divider>
                <el-form-item v-if="hasChild" class="t-children"
                              v-for="(child,index) in form.children" :label="`语言${index + 1}`" :key="child.id"
                              prop="translateVal">
                    <div class="sel">
                        <el-select @change="handleChangeChildLanguage" filterable clearable v-model="child.languageCode"
                                   placeholder="请选择目标语言">
                            <el-option v-for="dict in languageMinus||[]" :key="dict.languageId"
                                       :label="`${dict.languageCode}-${dict.zhName}`"
                                       :value="dict.languageCode"
                                       :disabled="dict.disabled"
                            />
                        </el-select>
                    </div>
                    <div class="ipt">
                        <el-input v-model="child.translateVal" :disabled="child.disabled" placeholder="请输入值"/>
                    </div>
                    <div class="oper">
                        <el-button
                                v-if="(index + 1 === form.children.length) && (form.children.length !== languageList.length)"
                                @click="handleAddChild" type="success"
                                :icon="Plus"/>
                        <el-button @click="handleRemoveChild(index)" type="danger" :icon="Delete"/>
                    </div>

                </el-form-item>
                <el-form-item v-else>
                    <el-button @click="handleAddChild" type="success" :icon="Plus"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 翻译导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="30%" append-to-body>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                       :action="upload.url + '?productId=' + queryParams.productId" :disabled="upload.isUploading"
                       :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
                       drag>
                <el-icon class="el-icon--upload">
                    <upload-filled/>
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <!--                        <div class="el-upload__tip">-->
                        <!--                            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
                        <!--                        </div>-->
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                 @click="importTemplate">下载模板
                        </el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Translate">
import {
    getTranslate,
    delTranslate,
    addTranslate,
    updateTranslate,
    topVersionListApi,
    translateApi, myListTranslate
} from "@/api/business/Translate";
import {parseTime} from "@/utils/tlate";
import {computed, getCurrentInstance, reactive, ref, toRefs} from "vue";
import {selectListProduct} from "@/api/business/Product";
import {selectListLanguage} from "@/api/business/Language";
import {Delete, Plus} from '@element-plus/icons-vue';
import {nanoid} from 'nanoid'
import useUserStore from "@/store/modules/user";
import {getToken} from "@/utils/auth";
import {useRoute} from "vue-router";
import {maxlength} from "@/config";

const {proxy} = getCurrentInstance();

const languageList = ref([])
const productList = ref([]);
const TranslateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const currentSelectedLanguage = ref([])
const route = useRoute();
const data = reactive({
    form: {
        children: []
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: route.query?.productId ? Number(route.query?.productId) : null,
        languageCode: null,
        translateVal: null,
    },
    rules: {
        productId: [
            {required: true, trigger: 'blur', message: "请选择翻译产品"}
        ],
        languageCode: [
            {required: true, trigger: 'blur', message: "请选择语言"}
        ],
        translateVal: [
            {required: true, trigger: 'blur', message: "请输入翻译值"}
        ]
    }
});

const {queryParams, form, rules} = toRefs(data);
/**
 * 是否有子集
 */
const hasChild = computed(() => {
    return form.value.children && form.value.children.length > 0
})
/**
 * 差集计算 所有语言 - 当前已选
 */
const languageMinus = computed(() => {
    const arr = languageList.value.map(x => {
        // 如果已经存在了
        if (currentSelectedLanguage.value.indexOf(x.languageCode) !== -1) {
            return {
                ...x,
                disabled: true
            }
        } else {
            return x;
        }
    });
    arr.sort((a, b) => Number(a.disabled) - Number(b.disabled))
    return arr;
})
/**
 * 子集的语言更新
 */
const handleChangeChildLanguage = (val) => {
    currentSelectedLanguage.value.length = 0;//清空
    form.value.children.forEach(child => {
        if (child.languageCode) {
            currentSelectedLanguage.value.push(child.languageCode)
        }
    })
    const set = new Set(currentSelectedLanguage.value);//设置唯一
    currentSelectedLanguage.value = Array.from(set);//转为数组

    const data = {
        productId: form.value.productId,
        q: form.value.translateVal,
        from: form.value.languageCode,
        to: val,
        toList: [val]
    }
    const index = computedCurrentLanguageCodeWhereInChild(val);
    if (index !== -1) {
        form.value.children[index].disabled = true;//赋值
    }
    val && getTranslateValue(data, index);//获取翻译值
}
/**
 * 计算当前语言在子集中的索引
 * @param languageCode
 */
const computedCurrentLanguageCodeWhereInChild = (languageCode) => {
    return form.value.children.findIndex(x => x.languageCode === languageCode)
}
/**
 * 添加子集
 */
const handleAddChild = () => {
    if (form.value.children.length >= languageList.value.length) return;
    proxy.$refs["TranslateRef"].validate(valid => {
        if (valid) {
            form.value.children.push({
                languageCode: null,
                translateVal: "",
                id: nanoid(),
                disabled: true
            })
            handleChangeChildLanguage();//更新
        }
    })
}

/**
 * 移除子集
 */
const handleRemoveChild = (index) => {
    form.value.children.splice(index, 1)
    handleChangeChildLanguage();//更新
}

/**
 * 获取翻译值
 * q
 * from
 * to
 */
const getTranslateValue = (data, index) => {
    if (!data.q || !data.from || !data.to) return;
    translateApi(data).then(res => {
        // 如果能找到
        if (index !== -1) {
            form.value.children[index].translateVal = res.data;//赋值
        }
    }).finally(() => {
        if (index !== -1) {
            form.value.children[index].disabled = false;//赋值
        }
    })
}

/** 查询翻译版本列表 */
function getList() {
    loading.value = true;
    if (useUserStore().id === 1) {
        topVersionListApi(queryParams.value).then(response => {
            TranslateList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    } else {
        myListTranslate(queryParams.value).then(response => {
            TranslateList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        })
    }
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        translateId: null,
        productId: route.query?.productId ? Number(route.query?.productId) : null,
        userId: null,
        parentId: null,
        stringKey: null,
        languageCode: null,
        translateVal: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        children: []
    };
    proxy.resetForm("TranslateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.translateId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加翻译版本";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _translateId = row.translateId || ids.value
    getTranslate(_translateId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改翻译版本";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["TranslateRef"].validate(valid => {
        if (valid) {
            if (form.value.translateId != null) {
                updateTranslate(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addTranslate(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _translateIds = row.translateId || ids.value;
    proxy.$modal.confirm('是否确认删除翻译版本编号为"' + _translateIds + '"的数据项？').then(function () {
        return delTranslate(_translateIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    });
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('business/Translate/exportAll', {
        ...queryParams.value,
        userId: useUserStore().id === 1 ? null : useUserStore().id
    }, `Translate_${new Date().getTime()}.xlsx`)
}

/**
 * 导出单条数据
 */
function handleExportSimple(row) {
    proxy.download('business/Translate/exportAll', {
        stringKey: row.stringKey
    }, `Translate_${new Date().getTime()}.xlsx`)
}

/**
 * 获取所有产品
 */
function getSelectListProduct() {
    selectListProduct().then(res => {
        productList.value = res.data;
    })
}

/**
 * 获取全部语种
 */
function getSelectListLanguage() {
    selectListLanguage().then(res => {
        languageList.value = res.data.map(x => {
            return {...x, disabled: false}
        });
    })
}

/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: {Authorization: "Bearer " + getToken()},
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/business/Translate/importAll"
});

/** 下载模板操作 */
function importTemplate() {
    proxy.download("business/Translate/importTemplate", {}, `translate_template_${new Date().getTime()}.xlsx`);
};

/** 导入按钮操作 */
function handleImport() {
    upload.title = "翻译导入";
    upload.open = true;
};

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
    getList();
};
getSelectListLanguage();
getSelectListProduct();
getList();
</script>
<style scoped lang="scss">
.t-children {
  div {
    margin-right: 20px;

    &.ipt {
      width: 30%;
    }
  }

  :deep(.el-form-item__content) {
    display: flex;
  }
}
</style>
